<template>
  <view class="TableWrap">
    <uni-table class="Table">
      <uni-tr>
        <uni-th class="Th" v-if="checkEnable()"></uni-th>
        <uni-th
          class="Th"
          v-for="(item, index) of columns"
          :key="index"
          :style="{ width: item.width }"
        >
          {{ item.title }}
        </uni-th>
      </uni-tr>
      <uni-tr
        v-for="(row, rowIndex) of dataSource"
        :key="rowIndex"
        @click="() => rowClickHandler(row, rowIndex)"
      >
        <uni-td class="Td" v-if="checkEnable()">
          <checkbox @click="() => itemCheck(row)" />
        </uni-td>

        <uni-td
          class="Td"
          v-for="(column, colIndex) of columns"
          :key="colIndex"
        >
          <view v-if="column.dataIndex" v-html="row[column.dataIndex]" />
        </uni-td>
      </uni-tr>
    </uni-table>
  </view>
</template>

<script lang="ts">
import Vue from '@/utils/Vue';
import { PropType } from 'vue';

interface IData {
  selectedDic: { [key: string]: any };
}
export interface ITableColumnProps {
  title: string;
  dataIndex?: string;
  width?: string;
  slot?: string;
}
export default Vue.extend({
  data(): IData {
    return {
      selectedDic: {},
    };
  },
  components: {},
  props: {
    onRowClick: {
      type: Function as PropType<(item: any, rowIndex: number) => void>,
      required: false,
    },

    itemKey: {
      type: String,
      default: 'id',
    },
    columns: Array as PropType<ITableColumnProps[]>,
    dataSource: Array as PropType<any[]>,

    onCheckChange: {
      type: Function as PropType<
        ((keys: any[], rows: any[]) => void) | undefined
      >,
      required: false,
    },
    disabledCheck: {
      type: Boolean,
      default: false,
    },
  },
  methods: {
    rowClickHandler(item: any, rowIndex: number) {
      if (this.onRowClick) {
        this.onRowClick(item, rowIndex);
      }
    },

    checkEnable() {
      return this.onCheckChange && !this.disabledCheck;
    },

    itemCheck(item: any) {
      const key = item[this.itemKey];
      const { selectedDic, itemKey, onCheckChange } = this;
      if (selectedDic[key]) {
        delete selectedDic[key];
      } else {
        selectedDic[key] = item;
      }

      if (onCheckChange) {
        onCheckChange(Object.keys(selectedDic), Object.values(selectedDic));
      }
    },
  },
});
</script>

<style lang="less">
.TableWrap {
  width: 100%;
  .Table {
    width: 100%;
    border-collapse: collapse;
    font-size: 16px;
    .Td,
    .Th {
      border: 1px solid #efeef3;
      padding: 10px 5px;
      color: black;
    }
    .Th {
      background: #ecf2ff;
      color: #5c5d6d;
      font-weight: normal;
    }
  }
}
</style>
